package com.faner.fast.common.controller;

import com.faner.fast.util.R;
import com.faner.fast.websocket.WsHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Optional;

@Validated
@RestController
@RequestMapping("/websocket")
@RequiredArgsConstructor
@Api(value = "websocket", tags = "工具:websocket")
public class WebsocketController {

    private final WsHandler wsHandler;

    @ApiOperation("广播消息")
    @RequestMapping(value = "send",method= {RequestMethod.GET})
    public R index() {
        Optional<WebSocketSession> session = wsHandler.getSessions().stream().findFirst();
        if (session.isPresent()) {
            try {
                wsHandler.sendMessage(session.get(), "对第一个会话发送了一条消息");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 省略其它代码
        return R.ok();
    }

    @ApiOperation("对第一个分组发送了一条消息")
    @RequestMapping(value = "broad",method= {RequestMethod.GET})
    public R broadCastToGroup() {
        try {
            wsHandler.broadCastToGroup(1, "对第一个分组发送了一条消息");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 省略其它代码
        return R.ok();
    }
}
